package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 王磊
 * @date 2022/5/10
 */
@Slf4j
@RequestMapping("/common")
@RestController
public class DownloadImgController {

    @Value("${reggie.path}")
    private String path;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //获取图片名称
        String filename = file.getOriginalFilename();
        //UUID生成随机图片名
        filename = UUID.randomUUID()+filename.substring(filename.lastIndexOf("."));
        //将文件转存
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        System.out.println(path+filename);
       file.transferTo(new File(path+filename));
        return R.success(filename);
    }



    @GetMapping ("/download")
    public void download(String name,HttpServletResponse response) throws IOException {
        FileInputStream inputStream = new FileInputStream(path+name);
        ServletOutputStream outputStream = response.getOutputStream();
        int bin;
        byte[] bytes = new byte[1024];
        while ((bin=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,bin);
        }
    }
}
